package com.sigmazero13.gameutils;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.sigmazero13.gameutils.GameTimerService.LocalBinder;
import com.sigmazero13.gameutils.model.GameInfo;
import com.sigmazero13.gameutils.utils.GameNameAdapter;

public class GameTimerView extends Activity {

	private GameTimerService mService;
	boolean mBound = false;
	private Button startStopButton;
	private Timer refreshTimer;
	private TextView timerText;
	private Spinner gameSpinner;
	private List<GameInfo> games;
	private AlertDialog endDialog;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.game_timer);
		
		Bundle bundle = getIntent().getExtras();
		int gameId = 0;
		if (bundle != null) {
			gameId = bundle.getInt("game_id", 0);
		}
		
		games = ((BoardGameUtilsApp)GameTimerView.this.getApplication()).getDbHelper().selectAllGames(); 
		
		gameSpinner = (Spinner) findViewById(R.id.record_game_spinner);
		GameNameAdapter adapter = new GameNameAdapter(this, R.layout.list_item, games);
		adapter.setDropDownViewResource(R.layout.list_item);
		gameSpinner.setAdapter(adapter);
		if (gameId > 0) {
			setGame(gameId);
		} else {
			gameId = ((GameInfo)gameSpinner.getSelectedItem()).getGameId();
		}
		
		gameSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				if (mBound) {
					mService.setGameName(((GameInfo)gameSpinner.getSelectedItem()).getName());
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				if (mBound) {
					mService.setGameName("");
				}
			}
		});
		
		timerText = (TextView)findViewById(R.id.timer_text);
		
		startStopButton = (Button)findViewById(R.id.button_timer_start_stop);
		startStopButton.setOnClickListener(new OnClickListener() {		
			@Override
			public void onClick(View v) {
				if (mBound) {
					Integer newText = 0;
					mService.setGameName(((GameInfo)gameSpinner.getSelectedItem()).getName());
					
					if (mService.isRunning()) {
						mService.stopTimer();
						if (mService.getElapsedSeconds() > 0) {
							newText = R.string.continue_timer;
						} else {
							newText = R.string.start_timer;
						}
					} else {
						mService.startTimer();
						newText = R.string.pause_timer;
					}
					
					startStopButton.setText(newText);
				}
			}
		});
		
		endDialog = new AlertDialog.Builder(this)
			.setMessage(R.string.end_dialog_message)
			.setCancelable(true)
			.setPositiveButton(R.string.end_dialog_record, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					long minutes = mService.getElapsedSeconds()/60;
					mService.resetTimer();
					startStopButton.setText(R.string.start_timer);
					Intent i = new Intent();
					i.putExtra("game_id", ((GameInfo)gameSpinner.getSelectedItem()).getGameId());
					i.putExtra("game_length", minutes);
					setResult(RESULT_OK, i);
					finish();
				}})
			.setNeutralButton(R.string.end_dialog_endonly, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					mService.resetTimer();
					startStopButton.setText(R.string.start_timer);
				}})
			.setNegativeButton(R.string.end_dialog_cancel, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
				}
			})
			.create();
		
		Button endButton = (Button)findViewById(R.id.button_timer_end);
		endButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mBound) {
					if (mService.getElapsedSeconds() == 0) {
						Toast.makeText(GameTimerView.this, "The game has not started!", Toast.LENGTH_SHORT).show();
					} else {
						endDialog.show();
					}
				}
			}
		});
	}
	
	
	@Override
	protected void onStart() {
		super.onStart();
		Intent intent = new Intent(this, GameTimerService.class);
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
		
		refreshTimer = new Timer("GameTimer");
		
		final Runnable updateTask = new Runnable() {
			@Override
			public void run() {
				updateTimerText();
			}
		};
		
		refreshTimer.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				runOnUiThread(updateTask);
			}
		}, 1000, 1000);
	}
	
	
	@Override
	protected void onStop() {
		super.onPause();
		try {
			unbindService(mConnection);
		} catch (Exception e) {
			Log.d("GameTimerView.onPause", e.getMessage());
		}
		refreshTimer.cancel();
		refreshTimer.purge();
		refreshTimer = null;
	}
	
	
	private ServiceConnection mConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			LocalBinder binder = (LocalBinder) service;
			mService = binder.getService();
			mBound = true;
		}
		
		@Override
		public void onServiceDisconnected(ComponentName className) {
			mBound = false;
		}
	};
	
	
	private void setGame(int gameId) {
		for (int i = 0; i < games.size(); i++) {
			if (games.get(i).getGameId() == gameId) {
				gameSpinner.setSelection(i);
				break;
			}
		}
	}
	
	
	private void updateTimerText() {
		long curTime = mService.getElapsedSeconds();
		long seconds = curTime % 60;
		long minutes = (curTime / 60) % 60;
		long hours = curTime / 3600;
		
		timerText.setText(String.format("%02d:%02d:%02d",hours,minutes,seconds));
	}
	
}
